<?php
namespace app\index\controller;

use app\common\controller\IndexBase;
use app\common\model\UploadFilesModel;
use app\common\model\UserModel;
use app\common\service\LoginService;
use think\facade\View;

class User extends IndexBase
{
    #需token认证的操作
    protected $needAuth = ['*'];

    #不需token认证的操作
    protected $noAuth = [];

    public function initialize()
    {
        parent::initialize();
        $action = $this->request->action();
        View::assign('action', $action);
    }

    public function index()
    {
        $user = $this->getUser();
        return view('', compact('user'));
    }

    /**
     * 个人信息
     * @return \think\response\View
     */
    public function info()
    {
        $userModel = new UserModel();
        if( $this->request->isPost() ) {
            $data = [
                'id' => $this->uid,
                'avatar' => $this->request->post('avatar'),
                'nickname' => $this->request->post('nickname'),
                'intro' => $this->request->post('intro'),
            ];
            $result = $userModel->update($data);
            if( $result ) {
                retSuccess([], '操作成功');
            } else {
                retError('操作失败');
            }
        }

        $user = $userModel->where('id',$this->uid)->find();
        return view('', compact('user'));
    }

    /**
     * 修改密码
     * @return \think\response\View
     */
    public function password()
    {
        $userModel = new UserModel();
        if( $this->request->isPost() ) {
            $oldpassword = trim($this->request->post('oldpassword'));
            $user = $userModel->where('id',$this->uid)->find();
            if( xn_encrypt($oldpassword, $user['salt']) != $user['password'] ) {
                retError('旧密码不正确');
            }
            $password = trim($this->request->post('password'));
            $repassword = trim($this->request->post('repassword'));
            try {
                validate(\app\common\validate\Login::class)->scene('password')
                    ->check([
                        'password' => $password,
                        'repassword' => $repassword
                    ]);
                $data = [
                    'id' => $this->uid,
                    'password' => xn_encrypt($password, $user['salt']),
                ];
                $userModel->update($data);
            } catch ( \Exception $e) {
                retError($e->getMessage());
            }
            retSuccess([], '操作成功');
        }
        return view();
    }

    /**
     * 上传头像
     * @return \think\response\Json
     */
    public function uploadAvatar()
    {
        $model = new UploadFilesModel();
        $result = $model->upload('avatar');
        return json($result);
    }

    /**
     * 退出登录
     * @return void
     */
    public function logout()
    {
        $loginService = new LoginService();
        $loginService->userLogout();
        $this->redirect(url('index/index'));
    }
}